﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.CodeParser;
using DevExpress.Utils.MVVM;
using DevExpress.Utils.VisualEffects;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPrinting;
using LSQL;

namespace Shopfloormanagement
{
    class publicFunc
    {
        public static DataTable SelectedDatatable(DataTable dt, string Condition)
        {
            // 假设 dt 是原始 DataTable
            DataRow[] selectedRows = dt.Select(Condition);

            // 创建新 DataTable，结构与 dt 相同
            DataTable newDt = dt.Clone();

            // 将筛选出的行添加到新的 DataTable
            foreach (DataRow row in selectedRows)
            {
                newDt.ImportRow(row);
            }

            return newDt;

        }
        public static int MaxDepartmentLevel()
        {
            int max = 0;
            string query = "select max(departmentLevel) as maxLv from Departments";
            DataTable dt = SQL.ReturnDataTable(SystemInfo.SQL, query);
            max = (int)dt.Rows[0]["maxLv"];

            return max;
        }

        /// <summary>
        /// 查询针对修改issue的权限
        /// </summary>
        /// <param name="Dep">提出部门ID</param>
        /// <param name="resDep">责任部门ID</param>
        /// <param name="resPerson">责任人ID</param>
        /// <returns></returns>
        private bool LoadScope4issue(int resDep, int resPerson, int Dep)
        {
            ////获得这个问题部门的结构矩阵，即得到这个部门的上下级关系，父级部门
            //DataTable dtDepEmployee =


            return true;
            ////先确定是不是责任人
            //if (resPerson == SystemInfo.userID)
            //{
            //    return true;
            //}

        }

        // 定义ComboBoxItem类
        public class ComboBoxItem
        {
            public string DisplayName { get; set; }
            public object Tag { get; set; }

            // 构造函数，接受两个参数
            public ComboBoxItem(string displayName, object tag)
            {
                DisplayName = displayName;
                Tag = tag;
            }

            public override string ToString()
            {
                return DisplayName; // 这将用于显示在ComboBox中
            }
        }

        

        public static void InitImgCombobox(ComboBoxEdit cbox)
        {
            cbox.Properties.Items.Add("0%");
            cbox.Properties.Items.Add("25%");
            cbox.Properties.Items.Add("50%");
            cbox.Properties.Items.Add("75%");
            cbox.Properties.Items.Add("100%");

        }


        public static void ComboBoxInit(DataTable data, ComboBoxEdit cbox, string display, string value)
        {
            cbox.Properties.Items.Clear();
            foreach (DataRow row in data.Rows)
            {
                string displayName = row[display].ToString();
                string tagValue = row[value].ToString();
                cbox.Properties.Items.Add(new publicFunc.ComboBoxItem(displayName, tagValue));
            }
        }

        public static void SetComboBoxEditSelectedByTag(ComboBoxEdit comboBox, object tag)
        {
            foreach (var item in comboBox.Properties.Items)
            {
                if (item is ComboBoxItem comboItem && Equals(Convert.ToInt32(comboItem.Tag), tag))
                {
                    comboBox.SelectedItem = comboItem;
                    return;
                }
            }

            // 如果没有匹配项，可以选择清空或设置默认项
            comboBox.SelectedItem = null;
        }

        public static int GetTopicID(int TodoID)
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {TodoID}");
            if (dt.Rows.Count > 0)
            {
                int TopicID = (int)dt.Rows[0]["TopicID"];
                return TopicID;
            }
            else
            {
                return 0;
            }
        }

        public static void Write2Gridview(DataTable dt, GridControl gc, GridView gv)
        {
            gv.BeginDataUpdate();
            gc.DataSource = dt;
            gv.OptionsView.ShowIndicator = false;
            //gvDeviation.PopulateColumns();  // 确保生成列

            gv.Columns.Clear(); // 不要清除列，否则后面代码会出错

            gv.Columns.AddVisible("ID", "No.");
            gv.Columns.AddVisible("DateTime", "Date");
            gv.Columns.AddVisible("提出部门", "Assigned by");
            gv.Columns.AddVisible("TopicINFO", "Topic");
            gv.Columns.AddVisible("RootCause", "Root cause");
            gv.Columns.AddVisible("Now_Action", "Action");
            gv.Columns.AddVisible("负责部门", "Res. department");
            gv.Columns.AddVisible("负责人姓名", "Res. person");
            gv.Columns.AddVisible("DueDate", "Due on");
            gv.Columns.AddVisible("Status", "Status");

            //设置文本列不可编辑
            gv.Columns["ID"].OptionsColumn.AllowEdit = false;
            gv.Columns["DateTime"].OptionsColumn.AllowEdit = false;
            gv.Columns["提出部门"].OptionsColumn.AllowEdit = false;
            gv.Columns["TopicINFO"].OptionsColumn.AllowEdit = false;
            gv.Columns["RootCause"].OptionsColumn.AllowEdit = false;
            gv.Columns["Now_Action"].OptionsColumn.AllowEdit = false;
            gv.Columns["负责部门"].OptionsColumn.AllowEdit = false;
            gv.Columns["负责人姓名"].OptionsColumn.AllowEdit = false;
            gv.Columns["DueDate"].OptionsColumn.AllowEdit = true;
            gv.Columns["Status"].OptionsColumn.AllowEdit = true;  // 让图片列可编辑

            // 配置日期列
            var repositoryItemDateEdit = new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit();
            repositoryItemDateEdit.CalendarTimeProperties.DisplayFormat.FormatString = "yyyy-MM-dd";
            repositoryItemDateEdit.CalendarTimeProperties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            repositoryItemDateEdit.Mask.EditMask = "yyyy-MM-dd";
            repositoryItemDateEdit.Mask.UseMaskAsDisplayFormat = true;

            // 确保不重复添加 RepositoryItem
            if (!gc.RepositoryItems.Contains(repositoryItemDateEdit))
            {
                gc.RepositoryItems.Add(repositoryItemDateEdit);
            }

            // 创建 ImageComboBoxEdit
            var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

            // 添加预设图片
            ImageList imageList = new ImageList();
            imageList.Images.Add("image3", Properties.Resources.进度0);
            imageList.Images.Add("image3", Properties.Resources.进度25);
            imageList.Images.Add("image3", Properties.Resources.进度50);
            imageList.Images.Add("image3", Properties.Resources.进度75);
            imageList.Images.Add("image3", Properties.Resources.进度100);

            // 绑定图片到 ImageComboBoxEdit
            repositoryItemImageComboBox.SmallImages = imageList;
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 0%", 1, 0));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 25%", 2, 1));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 50%", 3, 2));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 75%", 4, 3));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 100%", 5, 4));


            gv.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;
            // 确保不重复添加 RepositoryItem
            if (!gc.RepositoryItems.Contains(repositoryItemImageComboBox))
            {
                gc.RepositoryItems.Add(repositoryItemImageComboBox);
            }


            // 正确设置列宽（使用真实列名）
            //gvActionPlan.Columns["isConfirmation"].Width = 50;
            gv.Columns["ID"].Width = 80;
            gv.Columns["DateTime"].Width = 100;
            gv.Columns["提出部门"].Width = 128;
            gv.Columns["TopicINFO"].Width = 380;
            gv.Columns["RootCause"].Width = 357;
            gv.Columns["Now_Action"].Width = 380;
            gv.Columns["负责部门"].Width = 128;
            gv.Columns["负责人姓名"].Width = 120;
            gv.Columns["DueDate"].Width = 100;
            gv.Columns["Status"].Width = 110;

            //设置字体
            gv.Appearance.Row.Font = new Font("Tahoma", 12, FontStyle.Regular);
            gv.Appearance.HeaderPanel.Font = new Font("Tahoma", 12, FontStyle.Bold);
            gv.Appearance.HeaderPanel.BackColor = Color.FromArgb(30, 42, 99);
            gv.Appearance.HeaderPanel.ForeColor = Color.FromArgb(0, 0, 0);

            //设置自动换行
            // 允许行高自动调整
            gv.OptionsView.RowAutoHeight = true;

            // 让所有行都能换行
            gv.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让特定列换行
            gv.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gv.Columns["RootCause"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gv.Columns["Now_Action"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gv.Columns["提出部门"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gv.Columns["负责部门"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gv.Columns["负责人姓名"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让单元格可以输入多行文本
            var memoEdit = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            gv.Columns["TopicINFO"].ColumnEdit = memoEdit;
            gv.Columns["RootCause"].ColumnEdit = memoEdit;
            gv.Columns["Now_Action"].ColumnEdit = memoEdit;
            gv.Columns["提出部门"].ColumnEdit = memoEdit;
            gv.Columns["负责部门"].ColumnEdit = memoEdit;
            gv.Columns["负责人姓名"].ColumnEdit = memoEdit;

            // 确保 RepositoryItem 绑定到 GridControl
            if (!gc.RepositoryItems.Contains(memoEdit))
            {
                gc.RepositoryItems.Add(memoEdit);
            }
            gv.EndDataUpdate();
        }

        public static void Init_ImageInButton(SimpleButton btn, Image img)
        {
            btn.ImageOptions.Image = new Bitmap(img, btn.Width - 3, btn.Height - 3);
        }

        public static void SetColorByRelation()
        {
            //根据规则写入SQDC的红绿
            DataTable dtRelation = SQL.ReturnDataTable3(SystemInfo.SQL, "SQDC_Relation", $"HomeDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
            if (dtRelation.Rows.Count > 0)
            {
                string S = dtRelation.Rows[0]["DepartmentID_S"].ToString();
                string Q = dtRelation.Rows[0]["DepartmentID_Q"].ToString();
                string D = dtRelation.Rows[0]["DepartmentID_D"].ToString();
                string C = dtRelation.Rows[0]["DepartmentID_C"].ToString();

                int[] S_array = S.Split(',').Select(s => int.Parse(s)).ToArray();
                int[] Q_array = Q.Split(',').Select(s => int.Parse(s)).ToArray();
                int[] D_array = D.Split(',').Select(s => int.Parse(s)).ToArray();
                int[] C_array = C.Split(',').Select(s => int.Parse(s)).ToArray();

                int Snum = 0;
                int Qnum = 0;
                int Dnum = 0;
                int Cnum = 0;
                //设定S
                for (int S_idx = 0; S_idx < S_array.Length; S_idx++)
                {

                    DataTable res = SQL.ReturnDataTableDist(SystemInfo.SQL, "S_Color", "Color_of_SQDC", $"DepartmentID = {S_array[S_idx]} and DateTime = '{DateTime.Now.Date.AddDays(-1)}' and Del_tag = 0");
                    if (res.Rows.Count > 0)
                    {
                        if (res.Rows[0]["S_Color"].ToString() == "Red")
                        {
                            Snum = Snum + 1;
                        }
                        else if (res.Rows[0]["S_Color"] == null)
                        {
                            Snum = -1;
                        }
                    }

                }
                //设定Q
                for (int Q_idx = 0; Q_idx < Q_array.Length; Q_idx++)
                {
                    DataTable res = SQL.ReturnDataTableDist(SystemInfo.SQL, "Q_Color", "Color_of_SQDC", $"DepartmentID = {Q_array[Q_idx]} and DateTime = '{DateTime.Now.Date.AddDays(-1)}' and Del_tag = 0");
                    if (res.Rows.Count > 0)
                    {
                        if (res.Rows[0]["Q_Color"].ToString() == "Red")
                        {
                            Qnum = Qnum + 1;
                        }
                        else if (res.Rows[0]["Q_Color"] == null)
                        {
                            Qnum = -1;
                        }
                    }

                }
                //设定D
                for (int D_idx = 0; D_idx < D_array.Length; D_idx++)
                {
                    DataTable res = SQL.ReturnDataTableDist(SystemInfo.SQL, "D_Color", "Color_of_SQDC", $"DepartmentID = {D_array[D_idx]} and DateTime = '{DateTime.Now.Date.AddDays(-1)}' and Del_tag = 0");
                    if (res.Rows.Count > 0)
                    {
                        if (res.Rows[0]["D_Color"].ToString() == "Red")
                        {
                            Dnum = Dnum + 1;
                        }
                        else if (res.Rows[0]["D_Color"] == null)
                        {
                            Dnum = -1;
                        }
                    }

                }
                //设定C
                for (int C_idx = 0; C_idx < C_array.Length; C_idx++)
                {
                    DataTable res = SQL.ReturnDataTableDist(SystemInfo.SQL, "C_Color", "Color_of_SQDC", $"DepartmentID = {C_array[C_idx]} and DateTime = '{DateTime.Now.Date.AddDays(-1)}' and Del_tag = 0");
                    if (res.Rows.Count > 0)
                    {
                        if (res.Rows[0]["C_Color"].ToString() == "Red")
                        {
                            Cnum = Cnum + 1;
                        }
                        else if (res.Rows[0]["C_Color"] == null)
                        {
                            Cnum = -1;
                        }
                    }

                }

                //设置颜色
                string[] Colors = new string[4];
                //设置S
                if (Snum == 0)
                {
                    Colors[0] = "Green";
                }
                else if (Snum == -1)
                {
                    Colors[0] = "";
                }
                else
                {
                    Colors[0] = "Red";
                }
                //设置Q
                if (Qnum == 0)
                {
                    Colors[1] = "Green";
                }
                else if (Qnum == -1)
                {
                    Colors[1] = "";
                }
                else
                {
                    Colors[1] = "Red";
                }
                //设置D
                if (Dnum == 0)
                {
                    Colors[2] = "Green";
                }
                else if (Dnum == -1)
                {
                    Colors[2] = "";
                }
                else
                {
                    Colors[2] = "Red";
                }
                //设置C
                if (Cnum == 0)
                {
                    Colors[3] = "Green";
                }
                else if (Cnum == -1)
                {
                    Colors[3] = "";
                }
                else
                {
                    Colors[3] = "Red";
                }
                DataTable dtColor = SQL.ReturnDataTable3(SystemInfo.SQL, "Color_of_SQDC", $"DepartmentID = {SystemInfo.readparentDep} and DateTime = '{DateTime.Now.Date.AddDays(-1)}'");
                if (dtColor.Rows.Count > 0)
                {
                    bool res = SQL.Update(SystemInfo.SQL, "Color_of_SQDC", $"S_Color = '{Colors[0]}',Q_Color = '{Colors[1]}',D_Color = '{Colors[2]}',C_Color = '{Colors[3]}'", $"ID = {(int)dtColor.Rows[0]["ID"]}");
                }
                else
                {
                    string columns = "FactoryID,DepartmentID,LevelID,DateTime,S_Color,Q_Color,D_Color,C_Color,Del_tag";
                    string values = $"{SystemInfo.readFactory},{SystemInfo.readparentDep},{SystemInfo.readLevel},'{DateTime.Now.Date.AddDays(-1)}','{Colors[0]}','{Colors[1]}','{Colors[2]}','{Colors[3]}',0";
                    int res = SQL.InsertReturnID(SystemInfo.SQL, "Color_of_SQDC", columns, values);

                }

            }
        }

        public static void ComboBoxValueChanged(ComboBoxEdit cbox, int tag2int)
        {
            var selectedItem = cbox.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                tag2int = Convert.ToInt32(tag);
            }
        }

        public static string ImageToBase64(Image image)
        {
            if (image == null)
                throw new ArgumentNullException(nameof(image));

            using (MemoryStream ms = new MemoryStream())
            {
                try
                {
                    // 创建图像副本避免GDI+错误
                    using (Bitmap bitmap = new Bitmap(image))
                    {
                        bitmap.Save(ms, ImageFormat.Jpeg);
                    }
                    byte[] imageBytes = ms.ToArray();
                    return Convert.ToBase64String(imageBytes);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException($"转换图像到Base64时发生错误: {ex.Message}", ex);
                }
            }
        }

        public static Image Base64ToImage(string base64String)
        {
            if (base64String.Length < 1)
            {
                return null;
            }
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream ms = new MemoryStream(imageBytes))
            {
                return Image.FromStream(ms);
            }
        }

        public static bool GetUserScope(int userID, int depID)
        {
            if (depID == 0)
            {
                return GetUserSuper(userID);
            }
            else
            {
                //根据部门ID，查询其上下级部门
                string query = $@"WITH RecursiveDept AS (
    -- 初始层：从目标部门开始
    SELECT 
        ID,
        DepartmentName,
        ParentDepartmentID,
        0 AS Level
    FROM departments
    WHERE ID = {depID}

    UNION ALL

    -- 递归层：查找父部门
    SELECT 
        d.ID,
        d.DepartmentName,
        d.ParentDepartmentID,
        rd.Level + 1
    FROM Departments d
    INNER JOIN RecursiveDept rd ON d.ID = rd.ParentDepartmentID
)
SELECT * FROM RecursiveDept
ORDER BY Level desc";
                DataTable dtDep = SQL.ReturnDataTable(SystemInfo.SQL, query);
                if (dtDep.Rows.Count > 0)
                {
                    string[] depIDArray = new string[dtDep.Rows.Count + 1];
                    depIDArray[0] = "0";
                    for (int i = 0; i < dtDep.Rows.Count; i++)
                    {
                        depIDArray[i + 1] = dtDep.Rows[i]["ID"].ToString();
                    }
                    string depIDs = string.Join(",", depIDArray);
                    DataTable dtScope = SQL.ReturnDataTable3(SystemInfo.SQL, "View_EmployeeDepartments", $"EmployeeID = {userID} and DepartmentID in ({depIDs})");
                    if (dtScope.Rows.Count > 0)
                    {
                        //先判断是否有Superviser
                        DataRow[] res4Super = dtScope.Select("Scope = 'Supervise'");
                        DataRow[] res4manage = dtScope.Select("Scope = 'Manage'");
                        DataRow[] res4edit = dtScope.Select("Scope = 'Edit'");

                        if (res4Super.Length > 0)
                        {
                            return true;
                        }
                        if (res4manage.Length > 0)
                        {
                            return true;
                        }
                        else if (res4edit.Length > 0)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }

        }

        public static bool GetUserSuper(int userID)
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "EmployeeDepartments", $"DepartmentID = 0 and Scope = 4 and EmployeeID = {userID}");
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static int AssignDepID(int todo)
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", $"ID = {todo}");
            if (dt.Rows.Count > 0)
            {
                return (int)dt.Rows[0]["提出部门ID"];
            }
            else
            {
                return 0;
            }
        }
        public static int ResDepID(int todo)
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", $"ID = {todo}");
            if (dt.Rows.Count > 0)
            {
                return (int)dt.Rows[0]["负责部门ID"];
            }
            else
            {
                return 0;
            }
        }
        public static int AssignPersonID(int todo)
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", $"ID = {todo}");
            if (dt.Rows.Count > 0)
            {
                return (int)dt.Rows[0]["Todo创建人ID"];
            }
            else
            {
                return 0;
            }
        }

        public static DataTable UserIncompleteAction(int userID)
        {
            string columns = "ID,DateTime,提出部门,TopicINFO,RootCause,TodoINFO,负责部门,负责人姓名,DueDate,Status";
            DataTable dt = SQL.ReturnDataTableDist(SystemInfo.SQL, columns, "View_Todo", $"负责人ID = {userID} and Status < 5 and isConfirmation = 0");
            return dt;
        }

        public static DataTable UserUnconfirmAction(int userID)
        {
            DataTable dtScope = SQL.ReturnDataTable3(SystemInfo.SQL, "EmployeeDepartments", $"EmployeeID = {userID} and Del_tag = 0 and Scope > 2");
            string[] idArray = new string[dtScope.Rows.Count];
            if (dtScope.Rows.Count > 0)
            {
                for (int i = 0; i < dtScope.Rows.Count; i++)
                {
                    idArray[i] = dtScope.Rows[i]["DepartmentID"].ToString();
                }
                string ids = string.Join(",", idArray);
                string columns = "ID,DateTime,提出部门,TopicINFO,RootCause,TodoINFO,负责部门,负责人姓名,DueDate,Status";
                DataTable dt = SQL.ReturnDataTableDist(SystemInfo.SQL, columns, "View_Todo", $"提出部门ID in ({ids}) and Status = 5 and isConfirmation = 0");
                return dt;
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ID");
                dt.Columns.Add("DateTime");
                dt.Columns.Add("提出部门");
                dt.Columns.Add("TopicINFO");
                dt.Columns.Add("RootCause");
                dt.Columns.Add("TodoINFO");
                dt.Columns.Add("负责部门");
                dt.Columns.Add("负责人姓名");
                dt.Columns.Add("DueDate");
                dt.Columns.Add("Status");
                return dt;
            }



        }
    }
}
